'use client';

import React, { useEffect, useState, useRef, useCallback } from 'react';
import { createPortal } from 'react-dom';
import { useCollaboration } from '@/hooks/use-collaboration';
import { useSocket } from '@/hooks/use-socket';
import { throttle } from 'lodash';
import { useAuth } from '@/hooks/use-auth'; // 导入useAuth钩子

interface CursorPosition {
  userId: string;
  userName: string;
  userColor: string;
  position: {
    from?: number;
    to?: number;
    index?: number;
  };
  timestamp: number;
}

interface CursorOverlayProps {
  editorRef: React.RefObject<HTMLDivElement>;
  documentId: string;
}

export function CursorOverlay({ editorRef, documentId }: CursorOverlayProps) {
  const [cursors, setCursors] = useState<CursorPosition[]>([]);
  const { user } = useAuth(); // 使用useAuth代替useCollaboration获取用户
  const { socket, isConnected, onCursorMoved } = useSocket();
  const cursorRefs = useRef<Map<string, HTMLDivElement>>(new Map());
  const editorContentRef = useRef<HTMLElement | null>(null);
  const requestRef = useRef<number | null>(null); // 用于动画帧请求
  
  // 查找并设置编辑器内容元素引用
  useEffect(() => {
    if (editorRef?.current) {
      // 获取编辑器的内容元素（通常是ProseMirror的根元素）
      const editorContent = editorRef.current.querySelector('.ProseMirror');
      if (editorContent) {
        editorContentRef.current = editorContent as HTMLElement;
      }
    }

    // 清理函数
    return () => {
      if (requestRef.current !== null) {
        cancelAnimationFrame(requestRef.current);
      }
    };
  }, [editorRef?.current]);
  
  // 监听光标移动事件
  useEffect(() => {
    if (!isConnected || !socket) return;
    
    const handleCursorMoved = (data: any) => {
      if (data.docId !== documentId || data.userId === user?.id) return;
      
      setCursors(prev => {
        // 更新或添加光标位置
        const existingIndex = prev.findIndex(c => c.userId === data.userId);
        if (existingIndex >= 0) {
          const newCursors = [...prev];
          newCursors[existingIndex] = {
            ...data,
            timestamp: Date.now()
          };
          return newCursors;
        }
        
        return [...prev, {
          ...data,
          timestamp: Date.now()
        }];
      });
    };
    
    const unsubscribe = onCursorMoved(handleCursorMoved);
    return unsubscribe;
  }, [isConnected, socket, documentId, user, onCursorMoved]);
  
  // 清理过期的光标（用户不活跃超过10秒）
  useEffect(() => {
    const cleanupInterval = setInterval(() => {
      const now = Date.now();
      setCursors(prev => prev.filter(cursor => (now - cursor.timestamp) < 10000));
    }, 5000);
    
    return () => clearInterval(cleanupInterval);
  }, []);
  
  // 使用requestAnimationFrame优化光标位置更新
  const updateCursorPositions = useCallback(() => {
    if (!editorContentRef.current) return;
    
    // 使用requestAnimationFrame来平滑动画
    const animateCursors = () => {
      try {
        cursors.forEach(cursor => {
          const cursorElement = cursorRefs.current.get(cursor.userId);
          if (!cursorElement) return;
          
          // 根据光标位置获取文本节点位置
          const editorView = (window as any).editorView;
          if (!editorView) return;
          
          // 使用编辑器视图来获取光标位置的坐标
          const pos = cursor.position.index || cursor.position.from || 0;
          const coords = editorView.coordsAtPos(pos);
          
          if (coords) {
            // 获取编辑器内容元素的边界
            const editorRect = editorContentRef.current!.getBoundingClientRect();
            
            // 设置光标元素的位置
            cursorElement.style.left = `${coords.left - editorRect.left}px`;
            cursorElement.style.top = `${coords.top - editorRect.top}px`;
            cursorElement.style.opacity = '1';
            
            // 光标选择范围处理
            if (cursor.position.from !== undefined && cursor.position.to !== undefined && cursor.position.from !== cursor.position.to) {
              // 如果存在选择范围，绘制选择区域
              const startCoords = editorView.coordsAtPos(cursor.position.from);
              const endCoords = editorView.coordsAtPos(cursor.position.to);
              
              // 创建或获取选择区域元素
              let selectionElement = cursorElement.querySelector('.cursor-selection') as HTMLElement;
              if (!selectionElement) {
                selectionElement = document.createElement('div');
                selectionElement.className = 'cursor-selection';
                selectionElement.style.position = 'absolute';
                selectionElement.style.pointerEvents = 'none';
                selectionElement.style.opacity = '0.3';
                selectionElement.style.backgroundColor = cursor.userColor;
                cursorElement.appendChild(selectionElement);
              }
              
              // 计算并设置选择区域的位置和尺寸
              // 简单实现，实际可能需要更复杂的计算以处理多行选择
              selectionElement.style.left = `${startCoords.left - editorRect.left}px`;
              selectionElement.style.top = `${startCoords.top - editorRect.top}px`;
              selectionElement.style.width = `${endCoords.left - startCoords.left}px`;
              selectionElement.style.height = `${endCoords.bottom - startCoords.top}px`;
              selectionElement.style.display = 'block';
            } else {
              // 如果没有选择范围，隐藏选择区域
              const selectionElement = cursorElement.querySelector('.cursor-selection') as HTMLElement;
              if (selectionElement) {
                selectionElement.style.display = 'none';
              }
            }
            
            // 用户名标签逻辑保持不变
            const label = cursorElement.querySelector('.cursor-label') as HTMLElement;
            if (label) {
              label.style.opacity = '1';
              // 3秒后淡出用户名标签，但不隐藏光标
              if (!label.dataset.fadeTimeout) {
                const timeout = setTimeout(() => {
                  label.style.opacity = '0';
                  delete label.dataset.fadeTimeout;
                }, 3000);
                label.dataset.fadeTimeout = timeout.toString();
              }
            }
          }
        });
        
        // 继续动画循环
        requestRef.current = requestAnimationFrame(animateCursors);
      } catch (error) {
        console.error('更新光标位置失败:', error);
        // 错误时停止动画循环，防止持续错误
        requestRef.current = null;
      }
    };
    
    // 启动动画循环
    if (requestRef.current === null) {
      requestRef.current = requestAnimationFrame(animateCursors);
    }
    
    return () => {
      // 清理动画帧
      if (requestRef.current !== null) {
        cancelAnimationFrame(requestRef.current);
        requestRef.current = null;
      }
    };
  }, [cursors, editorContentRef.current]);
  
  // 监听编辑器内容变化，更新光标位置
  useEffect(() => {
    if (!editorContentRef.current) return;
    
    // 启动光标位置更新
    updateCursorPositions();
    
    // 监听DOM变化和窗口大小变化
    const observer = new MutationObserver(() => {
      // 内容变化时，重新计算光标位置
      if (requestRef.current === null) {
        requestRef.current = requestAnimationFrame(updateCursorPositions);
      }
    });
    
    observer.observe(editorContentRef.current, {
      childList: true,
      subtree: true,
      characterData: true
    });
    
    // 窗口大小变化时更新位置
    window.addEventListener('resize', updateCursorPositions);
    
    return () => {
      observer.disconnect();
      window.removeEventListener('resize', updateCursorPositions);
      
      // 清理动画帧
      if (requestRef.current !== null) {
        cancelAnimationFrame(requestRef.current);
        requestRef.current = null;
      }
    };
  }, [updateCursorPositions, editorContentRef.current]);
  
  // 如果没有编辑器内容元素或没有其他用户的光标，不渲染任何内容
  if (!editorContentRef.current || cursors.length === 0) {
    return null;
  }
  
  // 使用Portal将光标元素直接渲染到编辑器内容元素中
  return createPortal(
    <>
      {cursors.map(cursor => (
        <div
          key={cursor.userId}
          ref={el => {
            if (el) cursorRefs.current.set(cursor.userId, el);
            else cursorRefs.current.delete(cursor.userId);
          }}
          className="absolute z-50 pointer-events-none"
          style={{
            opacity: 0,
            transition: 'top 0.1s ease, left 0.1s ease'
          }}
        >
          {/* 光标 */}
          <div
            className="absolute h-5 w-0.5 cursor-blink"
            style={{ backgroundColor: cursor.userColor }}
          />
          
          {/* 光标选择区域占位符 */}
          <div className="cursor-selection" style={{ display: 'none' }} />
          
          {/* 用户名标签 */}
          <div
            className="cursor-label absolute left-0 top-0 transform -translate-y-full px-2 py-1 rounded text-xs text-white whitespace-nowrap"
            style={{
              backgroundColor: cursor.userColor,
              opacity: 0,
              transition: 'opacity 0.3s ease'
            }}
          >
            {cursor.userName}
          </div>
        </div>
      ))}
      
      <style jsx global>{`
        .cursor-blink {
          animation: cursor-blink-animation 1s ease infinite;
        }
        
        @keyframes cursor-blink-animation {
          0%, 100% { opacity: 1; }
          50% { opacity: 0.5; }
        }
        
        .cursor-selection {
          position: absolute;
          border-radius: 2px;
          z-index: 40;
        }
      `}</style>
    </>,
    editorContentRef.current
  );
} 